package com.sykj.config.aop;

import com.sykj.util.redis.RedisUtil;
import com.sykj.util.reponse.CommonEnum;
import com.sykj.util.reponse.ResultBody;
import org.apache.commons.lang3.StringUtils;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;


/**
 * @program: BeautyClub
 * @description: aop切面类
 * @author: qiaoli
 * @create: 2020-07-24 08:58
 */
@Aspect
@Component
public class DuplicateSubmitAop {

    private Logger logger = LoggerFactory.getLogger(getClass());

    @Around("execution(* com.sykj.controller.*Controller.*(..)) && @annotation(ds)")
    public Object arround(ProceedingJoinPoint pjp, DuplicateSubmit ds) {
        try {
            ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
            String sessionId = RequestContextHolder.getRequestAttributes().getSessionId();
            HttpServletRequest request = attributes.getRequest();
            String key = sessionId + "-" + request.getServletPath() + (StringUtils.isEmpty(request.getQueryString()) ? "" : request.getQueryString());
            if (!RedisUtil.hasKey(key)) {// 如果缓存中有这个url视为重复提交
                Object o = pjp.proceed();
                RedisUtil.set(key, key, ds.time());
                return  o;
            } else {
                logger.error("重复提交  sessionId : {} url : {} queryString : {}" , sessionId , request.getServletPath() , request.getQueryString());
                return  new ResultBody(CommonEnum.AOP_REPETITION_ERROR);
            }
        } catch (Throwable e) {
            e.printStackTrace();
            logger.error("验证重复提交时出现未知异常!");

return  new ResultBody(CommonEnum.AOP_VERIFY_ERROR);
        }

    }

}
